// key-value 模型
public class HashBucket { 
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int value) {
            this.key = key;
            this.val = value;
        }
    }

    private Node[] array;
    private int usedSize;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;

    public HashBucket(){
        array = new Node[10];
    }

    public void push(int key, int val) {
        // 通过哈希函数计算哈希地址
        int index = key % array.length;
        // 看一下key是不是在当前数组下标存储过，如果有 要更新val值
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        Node node = new Node(key,val);
        // 头插
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if(loadFactor() > LOAD_FACTOR){
            resize(); // 扩容
        }
    }

    private void resize() {
        Node[] newArray = new Node[array.length * 2];
        // 重新哈希. 遍历数组的每个链表
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null){
                int newIndex = cur.key % newArray.length;
                // 开始头插
                Node curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }

    private double loadFactor() {
        return usedSize * 1.0 / array.length;
    }

    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

}